/*
 * Created on 2005-9-21
 * Last modified on 2009-9-5
 * www.YeQiangWei.com
 */

package com.yeqiangwei.commons.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import com.yeqiangwei.commons.util.ValidatorHelper;

/**
 * 
 * @author aroot
 *
 */
public class URL{

	public static final String separator = "/";
	
	public static void main(String args[]){
		System.out.println(Charset.UTF8.toString());
	}

	public static enum Charset {
		
		UTF8, GBK, GB2312, ISO8859;
		
		@Override
		public String toString(){
			switch(this){
			case UTF8:
				return "UTF-8";
			case ISO8859:
				return "ISO-8859";
			case GBK:
				return "GBK";
			default:
				return super.toString();
			}
		}
	}
	
	/**
	 * @deprecated
	 * link {@link @encode(String, String, String)}
     * 对URL中文进行转码 一般get方式查询参数用到
     * @param str 中文字符串
     * @param coder 编码方式，如 UTF-8\GBK
     * @return
     */
    public static String urlEncoder(String str, String coder){
    	if(ValidatorHelper.isEmpty(coder)){
             coder = "UTF-8";
        }
        if(!ValidatorHelper.isEmpty(str)){
        	try {
                return java.net.URLEncoder.encode(str, coder.toLowerCase());
            } catch (UnsupportedEncodingException e) {
                System.out.println(e.toString());
            }
        }
        return "";
    }
    
    public static String encode(String str, Charset charset, String def){
    	return encode(str, charset.toString(), def);
    }
    
    public static String encode(String str, String enc, String def){
    	if(!ValidatorHelper.isEmpty(str)){
        	try {
                return java.net.URLEncoder.encode(str, enc);
            } catch (UnsupportedEncodingException e) {
                return def;
            }
        } else {
        	return def;
        }
    }
    
    /**
     * @deprecated
     * link {@link #decode(String, String, String)}
     * 对URL中文进行反转码，一般get方式查询参数用到
     * @param str 中文字符串
     * @param coder 编码方式，如 UTF-8\GBK
     * @return
     */
    public static String urlDecoder(String str, String coder){
    	if(ValidatorHelper.isEmpty(coder)){
             coder = "UTF-8";
        }
        if(!ValidatorHelper.isEmpty(str)){
        	 try {
                 return java.net.URLDecoder.decode(str, coder);
             } catch (UnsupportedEncodingException e) {
            	 System.out.println(e.toString());
             }
        }
        return "";
    }

    public static String decode(String str, Charset charset, final String def)
    {
    	return decode(str, charset.toString(), def);
    }
    
    public static String decode(String str, String enc, final String def)
    {
    	if(ValidatorHelper.isEmpty(enc)){
    		enc = "UTF-8";
        }
        if(!ValidatorHelper.isEmpty(str)){
        	 try {
                 return java.net.URLDecoder.decode(str, enc);
             } catch (UnsupportedEncodingException e) {
            	 System.out.println(e.toString());
             }
        }
        return def;
    }
    
    /**
     * 取得请求带参数的URL的方法
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
	public static String getURI(HttpServletRequest request) {
        StringBuffer originalURL = request.getRequestURL();
        Map<String,String[]> parameters = request.getParameterMap();
        if (parameters != null && parameters.size() > 0) {
            originalURL.append("?");
            for (Iterator<String> iter = parameters.keySet().iterator(); iter.hasNext();) {
                String key = iter.next();
                String[] values = parameters.get(key);
                for (int i = 0; i < values.length; i++) {
                    originalURL.append(key).append("=").append(values[i]).append("&");
                }
            }
        }
        return originalURL.toString();
    } 
    
    
    /**
     * 取得基于主机名的url，定向根目录的域名。（端口自动识别）
     * @param request
     * @return
     */
    public static String getServerUrl(HttpServletRequest request) {
        String str = "http://" + request.getServerName();
        int port = request.getServerPort();
        if(port!=80){
            str = str + ":" + String.valueOf(port);
        }
        return str;
    } 
    
    
    /**
     * 根据提供的域名地址返回网页html内容
     * @param domain
     * @return
     */
    public static String getWebContent(String domain){
    	StringBuffer sb = new StringBuffer("");
		BufferedReader in = null;
		java.net.URL url = null;
        try{  
            url = new java.net.URL(domain);
            in =  new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8"));
            String line;
            while((line = in.readLine()) != null){
                sb.append(line);
            }
        }catch(Exception e) {
        	System.out.println(e.toString());
        }finally{
        	try {
				in.close();
			} catch (IOException e) {
				System.out.println(e.toString());
			}
        }
        if(sb.length()>0){
        	return sb.toString();
        }else{
        	return null;
        }
    }
    
    /**
     * @deprecated
     * @param domain
     * @param encoding
     * @return
     */
    public static String getWebContent2(String domain, String encoding){
    	StringBuffer sb = new StringBuffer("");
		BufferedReader in = null;
		java.net.URL url = null;
        try{  
        	url = new java.net.URL(domain);    
            in = new BufferedReader(new InputStreamReader(url.openStream(),encoding));
            String line;
            while((line = in.readLine()) != null){
                sb.append(line);
            }
        }catch(Exception e) {
        	System.out.println(e.toString());
        }finally{
        	try {
				in.close();
			} catch (IOException e) {
				System.out.println(e.toString());
			}
        }
        return sb.toString();
    }
   
    /**
     * @deprecated
     * @param url
     * @param encoding
     * @return
     */
    public static String getWebContent(String url, String encoding){
        StringBuffer sb = new StringBuffer("");
        try {
 			sb.append(new String(HttpWrapper.getBytes(url),encoding));
		} catch (Exception e) {
			System.out.println(e.toString());
		}
        return sb.toString();         
    }
 
    public static String getHeader(HttpServletRequest request,  String str){
    	try{
    		return request.getHeader(str);
    	}catch(Exception e){
    		System.out.println(e.toString());
    	}
    	return null;
    }
  
}
